
package com.htj.erp.service;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.htj.erp.dao.HCustomerDao;
import com.htj.erp.dao.POrderDao;
import com.htj.erp.dao.ProductDao;
import com.htj.erp.dao.mybatis.POrderMapper;
import com.htj.erp.exception.BusinessException;
import com.htj.erp.model.jpa.HCustomer;
import com.htj.erp.model.jpa.POrder;
import com.htj.erp.model.jpa.Product;
import com.htj.erp.model.mybatis.POrderPO;
import com.htj.erp.util.ExcelUtil;
import com.htj.erp.vo.POrderVO;
import com.kedacom.security.service.GenericCpsService;
import com.kedacom.utils.ArrayUtil;
import com.kedacom.utils.DateFormatUtil;
import com.kedacom.utils.StringUtil;
/**
 * 
 *
 * 
 * POrderService
 * p_order service 处理类
 * 这个基本类一般继承com.kedacom.security.service.GenericCpsService
 * 如果自己实现转换类，通过重写getXXConveter方法。
 * chenghongtao
 * 2016-11-05 00:19:31
 * HTJ
 * @version 1.0.0
 *
 */
@Service
public class POrderService extends GenericCpsService<POrder,POrderPO,POrderVO,Long>  {

    
	@Resource
	private POrderDao pOrderDao;
	
	@Resource
	private POrderMapper pOrderMapper;
	
	
	@Resource
	private HCustomerDao hCustomerDao;
	
	@Resource
	private  ProductDao productDao;
	
	/**
	 * 获取jpa的dao
	 */
	@Override
	protected  POrderDao getEntityJpaDao ()
	{
		return this.pOrderDao;
	}
	 
	  
	/**
	 * 获取 mubatis 的dao
	 */
	@Override
	protected  POrderMapper getEntityDao ()
	{
		return this.pOrderMapper;
	}
	
	
	
	/**
	 * 
	 * saveOrUpdate 保存或者更新
	 * @param pOrderVO
	 * @return
	 *POrderVO
	 * @exception
	 * @since  1.0.0
	 */
	public POrderVO saveOrUpdate(POrderVO pOrderVO) throws Exception
	{
		pOrderVO.setTotalPrice(pOrderVO.getUnitPrice()*pOrderVO.getProductNum());
		pOrderVO.setFinnalPrice(pOrderVO.getTotalPrice() + pOrderVO.getDiscountPrice() + pOrderVO.getFreight());
		pOrderVO.setFinnalUnitPrice(new BigDecimal(pOrderVO.getFinnalPrice()).divide(new BigDecimal(pOrderVO.getProductNum()),2,RoundingMode.HALF_EVEN).setScale(2).floatValue());
	    if(pOrderVO.getId() == null || pOrderVO.getId() == 0L)
	    {
	    	pOrderVO.setStatus(0);
	        return this.add(pOrderVO);
	    }
	    else
	    {
	        return this.update(pOrderVO);
	    }
	    
	}
	
	
	
	public void importPorder(MultipartFile file) throws Exception
	{
		HSSFWorkbook rwb = null;
		try{
			List<POrder> orderList = new ArrayList<POrder>();
			System.out.println(file.getBytes().length);
			rwb = new HSSFWorkbook(new ByteArrayInputStream(file.getBytes()));
			HSSFSheet sheet = rwb.getSheetAt(0);
			int number = sheet.getLastRowNum();
			for(int i =1; i <= number; i++)
			{
				POrder o = new POrder();
				HSSFRow row = sheet.getRow(i);
				String cusName = ExcelUtil.getCellValue(row.getCell(3));
				HCustomer cus = hCustomerDao.findByCusName(cusName);
				if(cus == null)
					throw new BusinessException("未找到客户:" + cusName);
				o.setCusId(cus.getId());
				o.setCusName(cus.getCusName());
				o.setDepot("");
				o.setDiscountPrice(new Float(ExcelUtil.getCellValue(row.getCell(7))));
				o.setFinnalPrice(new Float(ExcelUtil.getCellValue(row.getCell(8))));
				o.setFreight(new Float(ExcelUtil.getCellValue(row.getCell(6))));
				o.setOrderCode(ExcelUtil.getCellValue(row.getCell(0)));
				o.setOrderTime(row.getCell(10).getDateCellValue());
				String productName = ExcelUtil.getCellValue(row.getCell(18));
				Product p = this.productDao.findByPName(productName);
				if(p == null)
					throw new BusinessException("未找到产品:" + productName);
				o.setProductId(p.getId());
				o.setProductName(p.getName());
				o.setProductNum(new Long(ExcelUtil.getCellValue(row.getCell(20))));
				o.setStatus(0);
				o.setTotalPrice(new Float(ExcelUtil.getCellValue(row.getCell(5))));
				o.setUnit(ExcelUtil.getCellValue(row.getCell(21)));
				o.setUnitPrice(new Float(ExcelUtil.getCellValue(row.getCell(19))));
				System.out.println(o.getOrderCode());
				if(new BigDecimal(o.getProductNum()).equals(BigDecimal.ZERO))
					throw new Exception(o.getOrderCode() + "数量为0");
				o.setFinnalUnitPrice(new BigDecimal(o.getFinnalPrice()).divide(new BigDecimal(o.getProductNum()),2,RoundingMode.HALF_EVEN).floatValue());
				orderList.add(o);
			}
			
			this.getEntityJpaDao().save(orderList);
			
		}finally{
			if(rwb != null)
				rwb.close();
		}
	}
	public void importPorder2(MultipartFile file) throws Exception
	{
		HSSFWorkbook rwb = null;
		try{
			List<POrder> orderList = new ArrayList<POrder>();
			System.out.println(file.getBytes().length);
			rwb = new HSSFWorkbook(new ByteArrayInputStream(file.getBytes()));
			HSSFSheet sheet = rwb.getSheetAt(0);
			int number = sheet.getLastRowNum();
			String dstr = DateFormatUtil.format(new Date(),"yyyyMMddHHmm");
			Date d = new Date();
			for(int i =1; i <= number; i++)
			{
				POrder o = new POrder();
				HSSFRow row = sheet.getRow(i);
				String cusName = ExcelUtil.getCellValue(row.getCell(0));
				if(StringUtil.isEmpty(cusName))
					break;
				HCustomer cus = hCustomerDao.findByCusName(cusName);
				if(cus == null)
					throw new BusinessException("未找到客户:" + cusName);
				o.setCusId(cus.getId());
				o.setCusName(cus.getCusName());
				o.setDepot("");
				o.setDiscountPrice(new Float(0));
				
				o.setFreight(new Float(0));
				
				o.setOrderTime(d);
				String productCode = ExcelUtil.getCellValue(row.getCell(1));
				Product p = this.productDao.findByCode(productCode);
				if(p == null)
					throw new BusinessException("未找到产品:" + productCode);
				o.setProductId(p.getId());
				o.setProductName(p.getName());
				o.setProductNum(new Long(ExcelUtil.getCellValue(row.getCell(6))));
				o.setUnit(p.getUnit());
				o.setUnitPrice(new Float(ExcelUtil.getCellValue(row.getCell(3))));
				o.setStatus(0);
				o.setTotalPrice(new Float(o.getProductNum()*o.getUnitPrice()));
				o.setFinnalPrice(new Float(o.getProductNum()*o.getUnitPrice()));
				o.setOrderCode(dstr + "-" + p.getCode());
				System.out.println(o.getOrderCode());
				if(new BigDecimal(o.getProductNum()).equals(BigDecimal.ZERO))
					throw new Exception(o.getOrderCode() + "数量为0");
				o.setFinnalUnitPrice(new BigDecimal(o.getFinnalPrice()).divide(new BigDecimal(o.getProductNum()),2,RoundingMode.HALF_EVEN).floatValue());
				orderList.add(o);
			}
			
			this.getEntityJpaDao().save(orderList);
			
		}finally{
			if(rwb != null)
				rwb.close();
		}
	}
	
	
	
	
	public void updateRecvDate(String ids,Date recvDate,String depot,String remark) throws Exception
	{
		String[] idArr = ids.split(",");
		
		List<POrder> porderList = this.getEntityJpaDao().findByIds(ArrayUtil.convertArray(idArr));
		for(POrder o : porderList)
		{
			if(o.getStatus() != 0)
			{
				throw new BusinessException(o.getOrderCode() + "已经收货");
			}
			
			o.setRecvDate(recvDate);
			o.setDepot(depot);
			o.setRemark(remark);
			o.setStatus(1);
		}
		this.getEntityJpaDao().save(porderList);
	}
	
	public void updateExpRecvDate(String ids,Date recvDate,String remark) throws Exception
	{
		String[] idArr = ids.split(",");
		
		List<POrder> porderList = this.getEntityJpaDao().findByIds(ArrayUtil.convertArray(idArr));
		for(POrder o : porderList)
		{
			o.setExpRecvDate(recvDate);
			o.setExpRecvRemark(remark);
		}
		this.getEntityJpaDao().save(porderList);
	}
	
	
	public void cacelSign(String ids)
	{
     String[] idArr = ids.split(",");
		
		List<POrder> porderList = this.getEntityJpaDao().findByIds(ArrayUtil.convertArray(idArr));
		for(POrder o : porderList)
		{
			o.setRecvDate(null);
			o.setDepot(null);
			o.setRemark(o.getRemark() + " \n" + DateFormatUtil.formatDate(new Date()) + " 取消签收");
			o.setStatus(0);
		}
		this.getEntityJpaDao().save(porderList);
	}
	
	public void delById (Long id) throws Exception {
		POrder order =this.getEntityJpaDao().findOne(id);
		if(order.getStatus() != null && order.getStatus() != 0)
		{
			throw new BusinessException(order.getOrderCode() + "已经签收，无法删除。");
		}
        getEntityJpaDao().delete(id);
    }

    public void delByIds (Long[] ids) throws Exception {
    	List<POrder> porderList = this.getEntityJpaDao().findByIds(ids);
    	for(POrder o : porderList)
		{
			if(o.getStatus() != null && o.getStatus() != 0)
			{
				throw new BusinessException(o.getOrderCode() + "已经签收，无法删除。");
			}
			
		}
        getEntityJpaDao().deleteByIds(ids);
    }
    
    
    public void addRemark(Long id,String remark)
    {
    	POrder order =this.getEntityJpaDao().findOne(id);
    	order.setRemark(order.getRemark() + "\n" + DateFormatUtil.format(new Date())+ ":" + remark);
    	this.getEntityJpaDao().save(order);
    }
}
